package com.zsr.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.entity.EduChapter;
import com.zsr.example.entity.EduSection;
import com.zsr.example.mapper.EduChapterMapper;
import com.zsr.example.service.EduChapterService;
import com.zsr.example.service.EduSectionService;
import com.zsr.example.util.constants.ErrorEnum;
import com.zsr.example.vo.ChapterVo;
import com.zsr.example.vo.VideoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-11-15
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduSectionService eduSectionService;

    /**
     * 根据课程id获取章节和小节
     *
     * @param courseId 课程id
     * @return
     */
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        //1. 根据课程id查询课程里所有的章节
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        chapterWrapper.orderByAsc("sort");
        List<EduChapter> chapters = this.list(chapterWrapper);

        //2. 根据课程id查询所有小节
        QueryWrapper<EduSection> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        List<EduSection> videos = eduSectionService.list(videoWrapper);

        return chapters.stream().map(a -> new ChapterVo(
                a.getId()
                , a.getTitle()
                , a.getDescription()
                , videos.stream().filter(b -> b.getChapterId().equals(a.getId()))
                .map(c -> new VideoVo(
                        c.getId()
                        , c.getTitle()
                        , c.getIsFree()
                        , c.getDuration()
                        , c.getVideoSourceId()
                )).collect(Collectors.toList())))
                .collect(Collectors.toList());

    }

    /**
     * 根据章节id删除章节
     *
     * @param id 章节id
     * @return
     */
    @Override
    public boolean removeChapterById(String id) {
        //根据id查询是否存在视频，如果有则提示用户尚有子节点
        if (eduSectionService.getCountByChapterId(id))
            throw new CommonJsonException(ErrorEnum.E_80003);
        //大于0删除成功
        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    /**
     * 根据课程id删除章节
     *
     * @param courseId 课程id
     */
    @Override
    public void removeChapterByCourseId(String courseId) {
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        this.remove(chapterWrapper);
    }
}
